import store from '@/store'
export const HOST_URL = 'https://jiaoyou2.10pay.cn'
const BASE_URL = 'https://jiaoyou2.10pay.cn/'
// export const HOST_URL = 'http://web.98250.com'
// const BASE_URL = 'http://web.98250.com/'
 
export const Request = (options) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'GET',
			data: options.data || {},
			header: {
				"Content-Type": "application/x-www-form-urlencoded"
			},
			success: (res) => {
				console.log(res)
				if(res.statusCode !== 200){
					
						console.log('看看什么接口');
						console.log(BASE_URL + options.url);
					return uni.showToast({
						title: '获取数据失败',
						icon: 'none'
					})
				}
				resolve(res)
			},
			fail: (err) => {
						// console.log(BASE_URL + options.url);
				uni.showToast({
					title: '网络错误，请检查网络！',
					icon: 'none'
				}) 	
				console.log(err.errMsg);
				if(err.errMsg == 'request:fail abort statusCode:-1 似乎已断开与互联网的连接。(-1009)'){
					uni.showModal({
						title: '系统提示',
						content: '当前设备无网络或网络较差',
						cancelText: '取消',
						confirmText: '确定',
						success: (res) => {
							if (res.confirm) {
								console.log(plus.os.name);
								if(plus.os.name == 'iOS'){
									plus.runtime.launchApplication({action:'app-settings://'},function(e){
										console.log(e.message);
									})
								}else{
									// #ifdef H5
									uni.navigateTo({
										url:'/pages/index/login'
									})
									// #endif
									// #ifdef APP-PLUS
									plus.runtime.quit()
									// #endif
								}
							} else if(res.cancel){
								console.log(plus.os.name);
								if(plus.os.name == 'iOS'){
									plus.runtime.launchApplication({action:'app-settings://'},function(e){
										console.log(e.message);
									})
								}else{
									// #ifdef H5
									uni.navigateTo({
										url:'/pages/index/login'
									})
									// #endif
									// #ifdef APP-PLUS
									plus.runtime.quit()
									// #endif
								}
							}
						}
					})
				}
				console.log(err)
				reject(err)
			}
		})
	})
}

export const Upimg = (data, callback) => {
	var user_id = uni.getStorage('userid');
	if (!data) return;
	var image = data.image;
	var water = 1;
	var thumb = 1;
	if (data.water === 0) {
		user_id = undefined;
		water = 0;
	}
	if (!callback || typeof callback != 'function') {
		console.log('未填写回调函数');
		return;
	}
	uni.uploadFile({
		url: HOST_URL + '/api/Tool/imagesUpload', //仅为示例，非真实的接口地址
		filePath: image,
		name: 'image',
		formData: {
			water: water,
			thumb: thumb,
			user_id: user_id
		},
		success: (uploadFileRes) => {
			var data
			try {
				data = JSON.parse(uploadFileRes.data)
				callback(data.data.image)
			} catch {
				console.log('解析失败')
			}
			
		}
	});
}



export const Upvideo = (url, callback) => {
	uni.uploadFile({
		url: HOST_URL + '/api/Tool/videoUpload', //仅为示例，非真实的接口地址
		filePath: url,
		name: 'video',
		success: (uploadFileRes) => {
			console.log(uploadFileRes);
			var data
			try {
				data = JSON.parse(uploadFileRes.data)
				callback(data.data.image)
			} catch {
				console.log('解析失败')
			}
			
		}
	});
}

// 获取单页内容
export const getPageContent = async (id, callback) => {
	const {data:res} = await Request({
		url: 'api/page/view',
		data: {
			id: id
		}
	})
	if (res.code == 200 && res.data) {
		callback(res.data)
	}
}

export const formatImage = (val) => {
	if(val){
		if(val.indexOf('/static/') == 0 || val.indexOf('http://') == 0 || val.indexOf('https://') == 0){
			return val
		} else {
			return HOST_URL + val
		}
	}else{
		return ''
	}
}



export const judgeQx = async (touserid, callback, chat) => {
    var sex = uni.getStorageSync('sex');
    var myuserid = uni.getStorageSync('uid');
    var cobj = {
        user_id: myuserid,
        to_user: touserid,
    }
    if (!chat) {
        cobj.type = 1; // 1为联系方式 0为聊天
    }
	const {data:ret} = await Request({
		url:'apis/home/user/vipsee',
		data: cobj
	})
	if (ret.code == 200) {
		if (ret.num == 0) {
			callback();
		} else {
			// 使用特权
			useTeQuan({
				msg: ret.msg,
				num: ret.num,
				touserid: touserid
			}, callback)
		}
	} else if (ret.code == 201) {
		uni.showModal({
			content: ret.msg,
			showCancel:false,
			success(res){
				if(res.confirm){
					uni.redirectTo({
						url:'/pages/renzheng/index'
					})
				}
			}
		})
	} else if (ret.code == 202) {
		uni.showModal({
			content:ret.msg,
			confirmText:'开通会员',
			success(res){
				if(res.confirm){
					uni.redirectTo({
						url:'/pages/member/index'
					})
				}
			}
		})
	} else if (ret.code == 205) {
		callback();
	} else if (ret.code == 220) {
		vipNumIsLimit({
			msg: ret.msg,
			money: ret.money,
			touserid: touserid
		}, callback)
	}
}



export const useTeQuan = (data, callback) => {
	var _this = this
    var num = data.num;
    var touserid = data.touserid;
    var myuserid = uni.getStorageSync('uid');
    var url = 'apis/home/user/getlink';
	uni.showModal({
		content:data.msg,
		async success(res){
			if(res.confirm){
				const {data:rets} = await Request({
					url:'apis/home/user/getlink',
					data:{
						user_id: myuserid,
						to_user: touserid,
					}
				})
				if (rets && rets.code == 200) {
					if (typeof callback == 'function') {
						callback();
					}
				} else {
					uni.showToast({
						title:rets.msg,
						icon:'none'
					})
				}
			}
		}
	})
}

export const vipNumIsLimit = (data, callback) => {
    var money = data.money;
    var touserid = data.touserid;
    var myuserid = uni.getStorageSync('uid');
    if (!money) {
        callback();
        return;
    }
    // 会员次数已达上限
    var obj = {
        msg: '您今日特权使用次数已用完,您可以支付' + money + '与该用户私聊。请确定以下操作',
        btn: ['购买', '取消'],
    };
	uni.showModal({
		title:'提示',
		content:'您今日特权使用次数已用完,您可以支付' + money + '与该用户私聊。请确定以下操作',
		confirmText:'购买',
		async success(res){
			if(res.confirm){
				const {data:rets} = await Request({
					url:'apis/home/user/buylian',
					data: {
						user_id: myuserid,
						to_user: touserid,
					}
				})
				if (rets && rets.code == 200) {
					callback();
				} else {
					uni.showToast({
						title:rets.msg,
						icon:'none'
					})
					if (rets.msg.indexOf('不足') != -1 || rets.msg.indexOf('不够') != -1) {
						showDetail('frame4/show_chong');
					}
				}
			}
		}
	})
}


export const pushMsg = (uid) => {
	if (!uid) return;
	var obj = {
		user_id: uid
	};
	Request({
		url:'apis/Home/Privatechat/getreadcount',
		data: {
			data: JSON.stringify(obj)
		}
	})
}



export const clearHtml = (s) => {
	// if (s.indexOf('/disk/uploads/audios/20') != -1) {
	// 	return '[语音]'
	// }
	if (!s) {
		return s;
	}
	var dd = s.replace(/<\/?.+?>/g, "");
	var dds = dd.replace(/ /g, "");
	return dds;
}
//微信小程序支付
export const WxMiniprogramPay = async (data) => {
	var price = data.money;
	var ordersid = data.number;
	const {data:rets} = await Request({
		url: 'api/Wxmini/app',
		data: {
			zongjia: price,
			danhao: ordersid,
			openid: uni.getStorageSync('openid')
		}
	})
	console.log(rets)
	if (rets && rets.code == 200) {
		var back_info = rets.data;
		uni.requestPayment({
			provider: 'wxpay',
			timeStamp: back_info.timeStamp,
			nonceStr: back_info.nonceStr,
			package: back_info.package,
			signType: back_info.signType,
			paySign: back_info.paySign, 
			success: function (res) {
				console.log('success:' + JSON.stringify(res));
				uni.setStorage({key: 'pay_authentication', data: 1})
				uni.switchTab({
					url:"/pages/ucenter/index"
				})
			},
			fail: function (err) {
				console.log('fail:' + JSON.stringify(err));
			},
			complete() {
				try {uni.hideLoading()} catch {}
			}
		});
	} else {
		uni.showToat({title:rets.msg,icon:false});
	}
}

//app微信支付
export const WeChatprogramPay = async (data) => {
	var price = data.money;
	var ordersid = data.number;
	const {data:rets} = await Request({
		url: 'api/Wechat/app',
		data: {
			zongjia: price,
			danhao: ordersid,
			openid: uni.getStorageSync('openid')
		}
	})
	console.log(rets);
	if (rets && rets.code == 200) {
		var back_info = rets.data;
		var orderInfo = {
		  "appid": back_info.appid,  // 应用ID（AppID）
		  "partnerid": back_info.partnerid,      // 商户号（PartnerID）
		  "prepayid": back_info.prepayid, // 预支付交易会话ID
		  "package": back_info.package,        // 固定值
		  "noncestr": back_info.noncestr, // 随机字符串
		  "timestamp":  back_info.timestamp,        // 时间戳（单位：秒）
		  "sign": back_info.sign // 签名，这里用的 MD5 签名
		};
		uni.requestPayment({
			"provider": 'wxpay',
			"orderInfo": orderInfo,
			success: function (res) {
				console.log('success:' + JSON.stringify(res));
				uni.setStorage({key: 'pay_authentication', data: 1})
				uni.switchTab({
					url:"/pages/ucenter/index"
				})
			},
			fail: function (err) {
				console.log('fail:' + JSON.stringify(err));
			},
			complete() {
				try {uni.hideLoading()} catch {}
			}
		});
	} else {
		uni.showToat({title:rets.msg,icon:false});
	}
}

//app 支付宝支付
export const AlipayprogramPay = async (data) => {
	var price = data.money;
	var ordersid = data.number;
	const {data:rets} = await Request({
		url: 'api/Alipay/tradeAppPay',
		data: {
			zongjia: price,
			danhao: ordersid
		}
	})
	console.log(rets);
	// var orderInfo = decodeURIComponent(rets)
	// console.log(orderInfo);
	// if (rets && rets.code == 200) {
		var back_info = rets;
		console.log(back_info);
		// console.log("back_info: " + JSON.stringify(back_info));
		uni.requestPayment({
			"provider": 'alipay',
			"orderInfo": back_info,
			success: function (res) {
				console.log('success:' + JSON.stringify(res));
			},
			fail: function (err) {
				console.log('fail:' + JSON.stringify(err));
			},
			complete() {
				try {uni.hideLoading()} catch {}
			}
		});
	// } else {
	// 	uni.showToat({title:rets.msg,icon:false});
	// }
}

//app Ios支付
export const IosprogramPay = async (data) => {
	var price = data.money;
	var ordersid = data.number;
	const {data:rets} = await Request({
		url: 'api/Apple/paypal',
		data: {
			zongjia: price,
			order: ordersid,
			apple_receipt:''
		}
	})
	if (rets && rets.code == 200) {
		var back_info = rets.data;
		uni.requestPayment({
			provider: 'appleiap',
			timeStamp: back_info.timeStamp,
			nonceStr: back_info.nonceStr,
			package: back_info.package,
			signType: back_info.signType,
			paySign: back_info.paySign,
			success: function (res) {
				console.log('success:' + JSON.stringify(res));
			},
			fail: function (err) {
				console.log('fail:' + JSON.stringify(err));
			},
			complete() {
				try {uni.hideLoading()} catch {}
			}
		});
	} else {
		uni.showToat({title:rets.msg,icon:false});
	}
}